﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QbservableCore.Serialization
{
    public static class ReflactionUtils
    {
        public static Type GetObservedType(this Type type)
        {
            Type observableType;
            if (type.IsInterface)
            {
                observableType =
                    (from interfaceType in type.GetInterfaces().Concat(new[] { type })
                     where IsIObservableType(interfaceType, null)
                     select interfaceType).FirstOrDefault();
            }
            else
            {
                observableType = type.FindInterfaces(IsIObservableType, null).FirstOrDefault();
            }
            if (observableType == null)
            {
                return null;
            }
            Type observedType = observableType.GetGenericArguments().First();
            return observedType;
        }

        private static bool IsIObservableType(Type interfaceType, object filterCriteria)
        {
            return interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IObservable<>);
        }
    }
}
